<template>
	<div style="padding:0 37px 0 44px">
    <div class="breadcrumb-father">
      <div class="new-breadcrumb">
        <router-link  :to="{path:'/welcome'}">
          <img src="../../../assets/imgs/Home.png" alt="">
        </router-link>
          <span>{{$t('mer.Client')}}</span>
        <span class="arrow">></span>
          <span>{{$t('mer.firm')}}</span>
      </div>
    </div>

    <div class="card-table">
			<div class="card-table-title">
        <svg aria-hidden="true" class="svg-icon svg-title-icon">
          <use xlink:href="#icon-firm"></use>
        </svg>
        <span>{{$t('mer.firm')}}</span>
			</div>
      <div>
        <!--搜索输入框-->
        <div class="search">
          <div class="search-input">
            <div class="date-wrapper">
              <label for="">{{$t('other.EstablishmentFrom3')}}</label>
              <div class="date-line"></div>
              <el-date-picker :editable=false value-format="yyyy-MM-dd" clearable type="date" placeholder="" v-model.trim="queryFirmData.startDate"></el-date-picker>
            </div>
            <div>
              <label for="">{{$t('other.EstablishmentTo')}}</label>
              <el-date-picker :editable=false value-format="yyyy-MM-dd" clearable type="date" placeholder="" v-model.trim="queryFirmData.endDate"></el-date-picker>
            </div>

            <div>
              <label for="">{{$t('firm.companyName')}}</label>
              <el-input v-model.trim="queryFirmData.name" clearable :maxlength=100 @keyup.enter.native="handleFilter(0)"></el-input>
            </div>

            <div>
              <label for="">{{$t('firm.companyID')}}</label>
              <el-input v-model.trim="queryFirmData.firmNumber" clearable :maxlength=100 @keyup.enter.native="handleFilter(0)"></el-input>
            </div>

            <div>
              <label for="">{{$t('firm.agent')}}</label>
              <!-- <el-input v-model.trim="queryFirmData.parentDistributorName" :maxlength=100 @keyup.enter.native="handleFilter(0)"></el-input> -->
              <el-select v-model="queryFirmData.parentDistributorId" popper-class='selectMer' filterable clearable :maxlength=100 :placeholder="$t('placeH.All')" >
                <el-option v-for="item in dNameOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </div>

            <div>
                <label for="">{{$t('firm.companyStatus')}}</label>
                <el-select v-model="queryFirmData.state" popper-class="el-select-custom" :placeholder="$t('placeH.All')" clearable class='filter-item condition'>
                    <el-option value="1" :label="$t('button.Enabled')"></el-option>
                    <el-option value="3" :label="$t('button.Suspended3')"></el-option>
                    <el-option value="0" :label="$t('search.Pending')"></el-option>
                    <el-option value="2" :label="$t('search.Rejected')"></el-option>
				</el-select>
            </div>

            <div class="search-btn-group">
              <el-button class="blue-btn mini2-btn" @click="handleFilter(0)">{{ $t('button.search') }}</el-button>
              <el-button class="blue-btn mini2-btn" @click="resetFilter">{{ $t('button.Reset') }}</el-button>
            </div>
          </div>
          
        </div>
        <!--商户列表-->
        <template>
          <div class="table-border">
            <div class="search-result-head">
              <span>{{ searchInfo }}</span>
              <span style="float:right;">
                <a href="javascript:void(0)" @click="refresh()" :title="$t('button.Refresh')"><icon-svg icon-class="shuaxin" id="refresh_icon"></icon-svg></a>
                <a href="javascript:void(0)" v-if="userType === '2' " @click="addFirm()" :title="$t('button.New')"><icon-svg icon-class="jia"></icon-svg></a>
              </span>
            </div>

          <el-table border :data="firmDatas" height=500 @cell-mouse-enter="showHandle" @cell-mouse-leave="hiddenHandle" v-loading="loading" :element-loading-text="$t('button.loading')" element-loading-background="rgba(255, 255, 255, 1)">
                <el-table-column type="index" fixed :label="$t('index.Number')" width="80">						    	
                </el-table-column>
                <el-table-column prop="name" :label="$t('index.name')" class-name="title_name">						    	
                </el-table-column>
                <el-table-column prop="firmNumber" :label="$t('firm.ID')">						    	
                </el-table-column>
                <el-table-column prop="state" :label="$t('firm.status')" :formatter="modifyState">						    	
                </el-table-column>
                <el-table-column prop="merchantSum" :label="$t('firm.merchantQty')">
                </el-table-column>
                <el-table-column width="160" prop="parentDistributorName" :label="$t('firm.agent')" show-overflow-tooltip> 
                </el-table-column>
                <el-table-column prop="addedDate" :label="$t('firm.registrationDate')">						    
                </el-table-column>
                <el-table-column fixed="right" class-name="animate_td handle-hidden-3">
				<template slot-scope="scope">
                  <a class="svg-link-class" :title="$t('button.Manage')" @click='showFirmDtails(scope.row.firmId,scope.row.state,scope.row.name)'>
                    <svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-yonghu"></use></svg>
                  </a>
                  <a class="svg-link-class" :title="$t('button.Enabled1')" v-if="scope.row.state==='3' && userType === '5' && userPhone !== '13501189583' && userPhone !== '15018955912' && userPhone !== '15219441946' " @click='stopOrStart(scope.row.state,scope.row.firmId)'>
                    <svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-qiyong"></use></svg>
                  </a>
                  <a class="svg-link-class" :title="$t('button.Suspended2')" v-if="scope.row.state==='1' && userType === '5' && userPhone !== '13501189583' && userPhone !== '15018955912' && userPhone !== '15219441946'  " @click='stopOrStart(scope.row.state,scope.row.firmId)'>
                    <svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-stop"></use></svg>
                  </a>
                </template>
              </el-table-column>
			</el-table>
          </div>
        </template>
      </div>
    </div>
		<div class="pagination-container">
      <el-pagination @size-change="handleSizeChange" background @current-change="handleCurrentChange" :current-page.sync="queryFirmData.page" :page-sizes="[15,20,30,50]" :page-size="queryFirmData.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="res.total"></el-pagination>
    </div>

	</div>
</template>
<script>
import { firmAll,enableOrDisable_firm } from "api/firm/index";
import { searchDistributor } from "api/businessManagement/merchant/index";

export default {
  
  data() {
    return {
      searchInfo:'',
      userType:localStorage.getItem('userType'),
      userPhone:localStorage.getItem('phone'),
      grade:localStorage.getItem('grade'),
      distributorId:localStorage.getItem('distributorId'),
      companyId:localStorage.getItem('companyId'),
      firmId:localStorage.getItem('firmId'),
      salesmanId:localStorage.getItem('salesmanId'),
      queryFirmData:{
        name:null,
        firmNumber:null,
        parentDistributorId:null,
        state:undefined,
        startDate:null,
        endDate:null,
        page:1,
        pageSize:15,
      },
      firmDatas:[],
      degIndex:1,
      rorateFlag:true,
      last_td_arr:[],
      res:[],
      msgAll:'',
      dNameOptions:[],
      oldPage: null,
      loading: true,
    };
  },
  watch:{
    'queryFirmData.page':function(newVal,oldVal){
        this.oldPage = oldVal;
    },
  },
  created() {
    if(localStorage.getItem('queryFirmData')){
      this.queryFirmData = JSON.parse(localStorage.getItem('queryFirmData'));
    }

    this.queryFirmAll(this.queryFirmData);
    $("#z_businessManagement .el-menu a li:eq(2)").addClass('is-active');

    this.searchInfo =  this.$t('mer.firm');
    // 查询所属代理商
    this.searchDistributor();

    
  },
  methods: {
    searchDistributor() {
      let searchData = {};
      if(this.userType == 2 && this.grade > 0) {
        searchData.distributorId = this.distributorId;
      }else if(this.userType == 5 || this.userType == 9 || this.grade == 0 || this.userType == 0 || this.userType == 11 ) {
        searchData.companyId = this.companyId;
      }else if(this.userType == 10) {
        searchData.firmId = this.firmId;
      }else if(this.userType == 8) {
        searchData.salesmanId = this.salesmanId;
      }

      searchDistributor(searchData)
        .then(res => {
          if (res.code == 0) {
            this.dNameOptions = res.value;
          }
        })
        .catch(() => {});
    },
    // 停用启用
    stopOrStart(state,firmId){
      if (state === "3") {
        this.msg = this.$t('hint.TheCompanyIsEnabled');
        this.msgAll = this.$t('hint.confirmToEnableThisMcompany');
      }
      if (state === "1") {
        this.msg = this.$t('hint.TheCompanyIsDisabled');
        this.msgAll = this.$t('hint.confirmToDisableThisMcompany');
      }
      state = state === '1' ? '3' : '1'; 
      this.$msgbox({
        title: this.$t("hint.Alert"),
        message: this.msgAll,
        showClose: false,
        closeOnClickModal:false,
        showCancelButton: true,
        confirmButtonText: this.$t("button.OK"),
        cancelButtonText: this.$t("button.Cancel"),
      }).then(() => {
        enableOrDisable_firm(state,firmId).then(res => {
          this.queryFirmAll(this.queryFirmData);
          if (res.code === 0) {
            this.$notify({
              title: this.$t("hint.Success"),
              message: this.msg,
              type: "success",
              duration: 2000
            });
          } else {
            this.queryFirmAll(this.queryFirmData);
          }
        });
      });
    },
    // 新增公司
    addFirm(){
      localStorage.setItem('queryFirmData',JSON.stringify(this.queryFirmData));
      this.$router.push({ path: "/handleFirm",query:{ id:'1',name:this.$t('mer.firm')} });
    },
    //公司详情
    showFirmDtails(firmId, state,name) {
      localStorage.setItem('queryFirmData',JSON.stringify(this.queryFirmData));
      this.$router.push({ path: "/handleFirm",query:{ id:'2',state:state,firmId:firmId,name:name } });
    },
    //格式化显示数据
    modifyState(row) {
      let state = row.state;
      if (state === "0") {
        return (state = this.$t("search.Pending"));
      } else if (state === "1") {
        return (state = this.$t("button.Enabled"));
      } else if (state === "2") {
        return (state = this.$t("search.Rejected"));
      } else if (state === "3") {
        return (state = this.$t("button.Suspended3"));
      }
    },
    showHandle(row, column, cell, event){
      // console.log(row);
      for(let i = 0;i<this.firmDatas.length;i++){
        if(this.firmDatas[i].firmId === row.firmId){
          this.tableIndex = i;
          const table_row = $(".el-table__fixed-right").find('.el-table__row')[i];
          $(table_row).find('td:last').removeClass('handle-hidden-'+ this.last_td_arr[i] );
          $(".el-table__fixed-right").addClass("fixed-column-" + this.last_td_arr[i] );
          $(".el-table__fixed-right").css("z-index","22");
          var action_div = $(table_row).find('td:last').children("div");
          $(action_div).stop().animate({"right": "0"});
        }
      }
      // 判断项目数目是否导致滚动条出现
      if(this.firmDatas.length <= 15){
        $(".el-table__fixed-right").addClass("right-zero");
      }else{
          $(".el-table__fixed-right").removeClass("right-zero");
      }
    },
    hiddenHandle(row, column, cell, event){
      const table_row = $(".el-table__fixed-right").find('.el-table__row')[this.tableIndex];
      $(".el-table__fixed-right").css("z-index","0");
      var action_div = $(table_row).find('td:last').children("div");
      $(action_div).stop().animate({"right": "-360px"});
    },
    handleFilter(sign,str){

      // 显示载入提示层
      this.loading = true;

      if(sign === 0) this.searchInfo =  this.$t('index.searchResults');
      const searchData = {};
      $.extend(searchData, this.queryFirmData);
      this.formatObj(searchData);
      this.queryFirmAll(searchData,str);

      if( str == 'CurrentChange' ){
        // 获取所有分页项数，循环去除选中样式，对点击前的项数添加选中样式
        let obj = $('.el-pager .number');
        for( let i = 0; i < obj.length; i++){
            if($(obj[i]).html() == this.oldPage) {
              console.log(this.oldPage);
              $(obj[i]).addClass('active');
            } else {
              $(obj[i]).removeClass('active');
            }
        }
      }

    },
    resetFilter(){
      //清空筛选条件
      this.queryFirmData.name = "";
      this.queryFirmData.firmNumber = "";
      this.queryFirmData.parentDistributorId = "";
      this.queryFirmData.state = "";
      this.queryFirmData.startDate = "";
      this.queryFirmData.endDate = "";
      this.queryFirmData.page = 1;
      this.queryFirmData.pageSize=15;
      this.searchInfo =  this.$t('mer.firm');
      this.handleFilter(1);
    },
    //刷新数据
    refresh(){
      const _that = this;
      if(this.rorateFlag){
        document.getElementById('refresh_icon').style.transform = 'rotate('+ this.degIndex * 360 +'deg)';
        this.handleFilter(1);
        this.rorateFlag = false;
        setTimeout(function (param) { _that.rorateFlag = true;_that.degIndex++; },1000);
      }
    },
    // 查询公司列表
    queryFirmAll(data,str){
      const _that = this;
      const search_Firm_Data = {};
      $.extend(search_Firm_Data, data);
      this.last_td_arr = [];

      if( this.userType == '2' && this.grade != 0 ) {
        if( !search_Firm_Data.parentDistributorId ){
          search_Firm_Data.parentDistributorId = localStorage.getItem('distributorId');
        }
      } else if ( this.grade == 0 ) {
        search_Firm_Data.companyId = localStorage.getItem('companyId');
      }

      if(this.userType === '5') search_Firm_Data.companyId = localStorage.getItem('companyId');
      if(this.userType === '10') search_Firm_Data.firmId = localStorage.getItem('firmId');

      this.formatObj(search_Firm_Data);

      firmAll(search_Firm_Data).then(res=>{
        this.firmDatas = res.value.list;
        this.res = res.value;

        // 特殊处理，防止以下索引取值不到导致载入层隐藏不掉
        setTimeout(function() {
          // 隐藏载入提示层
          _that.loading = false;
        },500)
        
        // 如果是分页触发，循环去除选中样式，对点击后的项数添加选中样式
        if( str == 'CurrentChange' ){
          let obj = $('.el-pager .number');
          for( let i = 0; i < obj.length; i++){
              if($(obj[i]).html() == this.queryFirmData.page) {
                $(obj[i]).addClass('active');
              } else {
                $(obj[i]).removeClass('active');
              }
          }
        }

        setTimeout(function (param) { 
            const td_last_child = $(".el-table__body-wrapper tr td:last-child");
            for(let i=0;i<td_last_child.length;i++){
              $(td_last_child[i]).removeClass('handle-hidden-3');
            }
            const td_fixed_last_child = $(".el-table__fixed-right tr td:last-child");
            for(let i=0;i<td_fixed_last_child.length;i++){
              if( $(td_fixed_last_child[i]).find('.svg-link-class').length === 1 ){
								$(td_fixed_last_child[i]).removeClass('handle-hidden-3').removeClass('handle-hidden-2').addClass('handle-hidden-1');
							} else if( $(td_fixed_last_child[i]).find('.svg-link-class').length === 2 ){
								$(td_fixed_last_child[i]).removeClass('handle-hidden-3').removeClass('handle-hidden-1').addClass('handle-hidden-2');
							} else if( $(td_fixed_last_child[i]).find('.svg-link-class').length === 3 ){
								$(td_fixed_last_child[i]).removeClass('handle-hidden-1').removeClass('handle-hidden-2').addClass('handle-hidden-3');
							} 
              _that.last_td_arr.push($(td_fixed_last_child[i]).find('.svg-link-class').length);

            }
					},500)
      }).catch(() => {});
    },
    //pageSize 改变时会触发
    handleSizeChange(val) {
      // this.$router.push({ path: "/firm", query:{ page:this.queryFirmData.page,pageSize: val } });
      this.queryFirmData.pageSize = val;
      this.handleFilter(1);
    },
    //currentPage 改变时会触发
    handleCurrentChange(val) {
      this.queryFirmData.page = val;
      this.handleFilter(1,'CurrentChange');
      // this.$router.push({ path: "/firm", query:{ page: val ,pageSize:this.queryFirmData.pageSize } });
    },
    formatObj(obj) {
      let arr = Object.keys(obj);
      for (let i = 0; i < arr.length; i++) {
        if (obj[arr[i]] === "") {
          obj[arr[i]] = null;
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
